package com.shopping.controller;

import com.shopping.common.Result;
import com.shopping.entity.User;
import com.shopping.service.UserService;
import com.shopping.dto.UserUpdateDTO;
import com.shopping.dto.UserQueryDTO;
import com.shopping.dto.PasswordResetDTO;
import com.shopping.dto.UserDTO;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/register")
    public Result<Boolean> register(@Valid @RequestBody User user) {
        boolean success = userService.register(user);
        return success ? Result.success(true) : Result.error("注册失败，用户名可能已存在");
    }

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> loginData) {
        String username = loginData.get("username");
        String password = loginData.get("password");

        try {
            String token = userService.login(username, password);
            if (token != null) {
                Map<String, Object> result = new HashMap<>();
                result.put("token", token);
                result.put("expiresIn", 24 * 60 * 60); // 24小时过期
                return Result.success(result);
            }
            return Result.error("用户名或密码错误");
        } catch (Exception e) {
            return Result.error("登录失败: " + e.getMessage());
        }
    }

    @GetMapping("/info")
    public Result<User> getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.findByUsername(username);
        if (user != null) {
            // 清除敏感信息
            user.setPassword(null);
            return Result.success(user);
        }
        return Result.error("用户不存在");
    }

    @GetMapping("/info/{username}")
    public Result<User> getUserInfo(@PathVariable String username) {
        User user = userService.findByUsername(username);
        return user != null ? Result.success(user) : Result.error("用户不存在");
    }

    @PutMapping("/info")
    public Result<Boolean> updateUserInfo(@RequestBody UserUpdateDTO updateDTO) {
        // 获取当前用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);

        if (currentUser == null) {
            return Result.error("用户不存在");
        }

        try {
            userService.updateUser(currentUser.getId(), updateDTO);
            return Result.success(true);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PutMapping("/password")
    public Result<Boolean> changePassword(@RequestBody Map<String, String> data) {
        // 这里应该修改密码
        // 暂时直接返回成功
        return Result.success(true);
    }

    @PutMapping("/points")
    public Result<Boolean> updatePoints(@RequestParam Long userId, @RequestParam Integer points) {
        boolean success = userService.updatePoints(userId, points);
        return success ? Result.success(true) : Result.error("更新积分失败");
    }

    @GetMapping("/list")
    public Result<Map<String, Object>> getUserList(UserQueryDTO queryDTO) {
        try {
            Page<UserDTO> page = userService.getUserList(queryDTO);
            Map<String, Object> result = new HashMap<>();
            result.put("list", page.getRecords());
            result.put("total", page.getTotal());
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取用户列表失败: " + e.getMessage());
        }
    }

    @PutMapping("/{userId}")
    public Result<Boolean> updateUser(@PathVariable Long userId, @RequestBody UserUpdateDTO updateDTO) {
        try {
            userService.updateUser(userId, updateDTO);
            return Result.success(true);
        } catch (Exception e) {
            return Result.error("更新用户信息失败: " + e.getMessage());
        }
    }

    @PutMapping("/{userId}/password")
    public Result<Boolean> resetUserPassword(@PathVariable Long userId, @RequestBody Map<String, String> data) {
        try {
            String newPassword = data.get("newPassword");
            if (newPassword == null || newPassword.trim().isEmpty()) {
                return Result.error("新密码不能为空");
            }
            PasswordResetDTO resetDTO = new PasswordResetDTO();
            resetDTO.setNewPassword(newPassword);
            userService.resetPassword(userId, resetDTO);
            return Result.success(true);
        } catch (Exception e) {
            return Result.error("重置密码失败: " + e.getMessage());
        }
    }

    @PutMapping("/{userId}/status")
    public Result<Boolean> toggleUserStatus(@PathVariable Long userId) {
        try {
            userService.toggleUserStatus(userId);
            return Result.success(true);
        } catch (Exception e) {
            return Result.error("切换用户状态失败: " + e.getMessage());
        }
    }
}